﻿using System;
using System.Collections.Generic;
using System.Configuration;
using System.Linq;
using System.Web;
using ProjBackEnd.DBInstance;
using ProjBackEnd.Areas.Sys.Models;
using System.IO;
using ProjBackEnd.Lib;
using System.Reflection;
using System.Data;
using System.Threading.Tasks;

namespace ProjBackEnd.DAL
{
    public class sysLogic
    {
        /// <summary>
        /// 数据库枚举
        /// </summary>
        public enum DataBaseName
        {
            /// <summary>
            /// 项目管理
            /// </summary>
            PROJ = 0
        }

        /// <summary>
        /// 获取数据库连接字符串
        /// </summary>
        /// <param name="enumDbName">数据库名</param>
        /// <returns>数据库连接字符串</returns>
        public static string GetConnString(DataBaseName enumDBName)
        {
            string strReturn = "";
            switch (enumDBName)
            {
                case DataBaseName.PROJ:
                    strReturn = ConfigurationManager.AppSettings["ConnPROJDB"];
                    break;
            }
            return strReturn;
        }

        /// <summary>
        /// 获取流水号
        /// </summary>
        /// <param name="_strReftp">流水号类别</param>
        /// <returns>成功返回正常流水号；失败返回 0</returns>
        public static int GetRefNo(string _strReftp)
        {
            if (_strReftp.Length > 6) throw new Exception("流水号类别超长");
            BaseCodeDataContext bcctx = new BaseCodeDataContext(GetConnString(DataBaseName.PROJ));
            try
            {
                int iRefCore = bcctx.SP_GETMASTERKEY(_strReftp.ToUpper() + "ID");
                if (iRefCore == 0) throw new Exception("获取流水号失败");
                return iRefCore;
            }
            catch (Exception ex)
            {
                DataUtil.WriteLog(MethodBase.GetCurrentMethod().Name, ex.Message + ";" + _strReftp);
                return 0;
            }
            finally { if (bcctx.Connection.State != ConnectionState.Closed) bcctx.Connection.Close(); }
        }

        public static string GetRefNo(string _strComcd, string _strReftp)
        {
            if (_strReftp.Length > 6) throw new Exception("流水号类别超长");
            if (_strComcd.Length > 4) throw new Exception("公司代码超长");
            BaseCodeDataContext bcctx = new BaseCodeDataContext(GetConnString(DataBaseName.PROJ));
            try
            {
                int iRefCore = bcctx.SP_GETMASTERKEY(_strReftp.ToUpper() + "REF");
                if (iRefCore == 0) throw new Exception("获取流水号失败");
                return _strComcd.ToUpper() + _strReftp.ToUpper() + iRefCore.ToString("0000000000");
            }
            catch (Exception ex)
            {
                DataUtil.WriteLog(MethodBase.GetCurrentMethod().Name, ex.Message + ";" + _strComcd + ";" + _strReftp);
                return "";
            }
            finally { if (bcctx.Connection.State != ConnectionState.Closed) bcctx.Connection.Close(); }
        }

    }
}